import requests, json


class BaiduApi:
    def __init__(self):
        self.API_KEY = "CtZTZJ6iK57wRSumL4vQ8cw6"
        self.SECRET_KEY = "6iPPi7jT4xfxGQAzIjY2UQPmBpFSSujb"

    def get_access_token(self):
        """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    # 身份证验证
    def idcard(self, picurl):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        # image 可以通过 get_file_content_as_base64("C:\fakepath\1.png",True) 方法获取
        payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false' % (
            picurl)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        print(response)
        print(response.status_code)
        if int(response.status_code) == 200:
            return response.text
        else:
            return False




    # 文字识别
    # def fontmessage(self, picurl):
    #     url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + self.get_access_token()
    #
    #     payload = 'url=%s&detect_direction=false&paragraph=false&probability=false' % (picurl)
    #     headers = {
    #         'Content-Type': 'application/x-www-form-urlencoded',
    #         'Accept': 'application/json'
    #     }
    #     response = requests.request("POST", url, headers=headers, data=payload)
    #     data = json.loads(response.text)
    #     name = data['words_result'][0]['words']
    #     code = data['words_result'][1]['words']
    #     return {"name": name, 'code': code}


bdapi = BaiduApi()




class BaiduFace():
    def __init__(self):
        self.API_KEY = "vGsQuolpCk0DogGBtuV5LJhK"
        self.SECRET_KEY = "vQHu7XW0cbu5Apu56d9LIXWkyxrLhmZU"

    def get_access_token(self):
        """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    def main(self, image1, image2):
        url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + self.get_access_token()

        payload = json.dumps([
            {
                "image": image1,
                "image_type": "BASE64"
            },
            {
                "image": image2,
                "image_type": "BASE64"
            }
        ], ensure_ascii=False)
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        score = json.loads(response.text)['result']['score']

        if float(score) > 90:
            return True
        else:
            return False


bdface = BaiduFace()

class BaiduText:

    def __init__(self):
        self.API_KEY = "LVGM06DkeBibwTaqob3t6i7n"
        self.SECRET_KEY = "7QRdD9jX9tR6yU39yzFmGQIKj6NTqZZY"



    def main(self,text):
        url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + self.get_access_token()

        payload = f'text={text}'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        print(response.text)

        if json.loads(response.text)['conclusionType'] == 1:
            return True
        else:
            return False


    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))


CheckText = BaiduText()

